/*
 * @Author: nns4
 * @Date: 2019-10-31 14:45:01
 * @LastEditors: nns4
 * @LastEditTime: 2019-12-03 15:27:22
 * @FilePath: /wxShop/src/libs/axios.js
 * @Description: 封装axios 请求
 */
import axios from 'axios'
import {
  Toast
} from 'vant';

class HttpRequest {
  constructor(baseUrl = baseURL) {
    this.baseUrl = baseUrl
    this.queue = {}
    this.loadingToast = ""
  }
  getInsideConfig() {
    const config = {
      baseURL: this.baseUrl,
      headers: {
        //
      }
    }
    return config
  }
  interceptors(instance, url, loading) {
    if (loading) {
      this.loadingToast = Toast.loading({
        message: '加载中...',
        forbidClick: true
      });
    }
    // 请求拦截
    instance.interceptors.request.use(config => {
      return config
    }, error => {
      this.loadingToast.clear()
      return Promise.reject(error)
    })
    // 响应拦截
    instance.interceptors.response.use(res => {
      if (loading) {
        this.loadingToast.clear()
      }
      const {
        data,
        status
      } = res
      return {
        data,
        status
      }
    }, error => {
      if (loading) {
        this.loadingToast.clear()
      }
      return Promise.reject(error)
    })
  }
  request(options, loading = false) {
    const instance = axios.create()
    options = Object.assign(this.getInsideConfig(), options)
    this.interceptors(instance, options.url, loading)
    return instance(options)
  }
}
export default HttpRequest